const router = require("koa-router")();
const dept = require("../models/deptsSchema");
const utils = require("../utils/utils");
router.prefix("/dept");

router.get("/list", async (ctx, next) => {
  const { deptName } = ctx.request.query;
  const params = {};
  if (deptName) params.deptName = deptName;
  let res = await dept.find(params);
  ctx.body = utils.success({ data: res });
});

// 菜单编辑、删除、新增功能
router.post("/operate", async (ctx) => {
  const { _id, dialogFormType, ...params } = ctx.request.body;
  let res, info;
  try {
    if (dialogFormType == "add") {
      //新增
      let res = await Menu.findOne(
        { $or: [{ menuName: params.menuName }] },
        "_id menuName"
      );
      if (res) {
        ctx.body = utils.fail({
          data: null,
          code: 400,
          msg: "检测到有重复角色,请勿重复添加",
        });
      } else {
        let menu = new Menu({
          parentId: [...params.parentId],
          ...params,
        });
        menu.save();
        ctx.body = utils.success({ data: null, msg: "添加成功", code: 200 });
      }
    } else if (dialogFormType == "edit") {
      //编辑
      params.updateTime = new Date();
      res = await Menu.findByIdAndUpdate(_id, params);
      info = "编辑成功";
    } else if (dialogFormType == "Del") {
      //删除
      res = await Menu.findByIdAndRemove(_id);
      await Menu.deleteMany({ parentId: { $all: [_id] } });
      info = "删除成功";
    }
    ctx.body = utils.success("", info);
  } catch (error) {
    ctx.body = utils.fail(error.stack);
  }
});
module.exports = router;
